import serial
import psutil
import sys
import glob
import config
import setting_get_set


class Bater_cpu:
    def set_save_config(self):
        if config.exit_set_config:
            for key in config.set_list_ket_config:
                config.settings[key] = config.settings[key]
            config.cmds["void"] = config.cmds_void
            setting_get_set.write_config("settings.json", config.settings)
            setting_get_set.read_config("config.json", config.cmds)

    def batar(self):
        battery = psutil.sensors_battery()
        plugged = battery.power_plugged
        percent = round(battery.percent)
        if not plugged:
            plugged = "Батарея не заряжается"
        elif percent == 100:
            plugged = "Батарея заряжена"
        elif plugged == 19:
            plugged = "Энергия"
        else:
            plugged = "Батарея заряжается"

        t = f"{plugged} {percent} процентов"
        return t

    def core_temp(self):
        o = psutil.sensors_temperatures()
        return o["coretemp"][0][1]

    def core_temp_info(self):
        try:
            text = ""
            temp = self.core_temp()
            if 25 <= temp < 50:
                text = f"Температура в порядке {temp} градусов"
            elif 50 <= temp <= 80:
                text = f"Температура повышена {temp}"
            elif temp > 80:
                text = f"Процессору хана  температура {temp} градусов"
            else:
                text = "Что-то пошло не так с процессором"
            return text
        except BaseException:
            return "Ошибка"

    def api_batar(self, **menu):
        text = ""
        if menu["menu"] == "batar":
            text = self.batar()
        elif menu["menu"] == "core_temp_info":
            text = self.core_temp_info()
        elif menu["menu"] == "core_temp()":
            text = str(self.core_temp())
        return text

    def __del__(self):
        pass


class MC:
    def __init__(self, speed=9600) -> None:
        self.ser = None
        self.flag_work = True
        self.searhc_port()

    def serial_write(self, value) -> str:
        try:
            if self.flag_work:
                b = value.encode("ASCII")
                self.ser.write(b)
                return ""
            else:
                self.searhc_port()
                return "Устройство не обнаружено"
        except BaseException:
            self.searhc_port()
            return "Устройство не обнаружено"

    def searhc_port(self, speed=9600):
        serial_port = self.__serial_ports()
        if len(serial_port) != 0:
            self.ser = serial.Serial(serial_port[0], speed, timeout=2)
            self.flag_work = True
        else:
            self.flag_work = False

    def serial_write_wrapper(self, list_data) -> str:
        if self.flag_work:
            self.serial_write(f"{','.join([str(data) for data in list_data])};")

    def serial_read(self):
        if self.flag_work:
            return self.ser.readline()
        else:
            return ""

    def __serial_ports(self) -> list:
        result = []
        ports = []

        if sys.platform.startswith("linux"):
            ports = glob.glob("/dev/tty[A-Za-z]*")

        if len(ports) != 0:
            for device_name, values in config.cmds["name_output_device"].items():
                if device_name in ports:
                    result.append(device_name)
                else:
                    pass

        return result

    def __del__(self):
        if self.flag_work:
            self.ser.close()


class Info_Core:
    def __init__(self):
        self.raz = "|\n\t\t|"
        self.raz0 = "\n\t\t|"

    def info_core_all(self) -> str:
        mess = (
            f"{self.info_basic()}{self.info_author()}{self.info_license()}"
            f"{self.info_add_verison()}{self.info_cmds()}{self.info_collection()}"
            f"{self.info_programms()}"
        )
        return mess

    def info_basic(self) -> str:
        mess = f"Версия ядра {config.version}"
        mess = f"{mess}\nИмя помощника {config.cmds['name'][0].upper()}"
        mess = f"{mess}\nОсновной голос {config.dict_value_str_voice['voice_name']}"
        mess = (
            f"{mess}\nАнглийский голос {config.dict_value_str_voice['voice_name_en']}"
        )
        return f"{mess}\n"

    def info_cmds(self) -> str:
        mess = ""
        mess = f"{mess}{'Список функций'.upper()}"
        for key, value in config.cmds_void.items():
            mess = f"{mess}\n{key}{self.raz0}{self.raz.join(value)}|"
        return f"{mess}\n"

    ""

    def info_programms(self) -> str:
        mess = ""
        mess = f"{mess}{'Список программ'.upper()}"
        # for key, value in config.cmds["os.cmd"].items():
        #    mess = f"{mess}\n{key}{self.raz0}{self.raz.join(value)}|"
        return f"{mess}\n"

    def info_collection(self) -> str:
        mess = ""
        mess = f"{mess}{'Список коллекций'.upper()}"
        for key, value in config.temporary_files.items():
            mess = f"{mess}\n{key}{self.raz0}{self.raz.join(value)}|"
        return f"{mess}\n"

    def info_add_verison(self) -> str:
        mess = f"В версии {config.version} добавлено {self.raz0} Добавить информацию ,что я добавил я ядро|"
        return f"{mess}\n"

    def info_license(self) -> str:
        mess = "Лицензия ПО пока еще не решил"
        return f"{mess}\n"

    def info_author(self) -> str:
        mess = "Автор Белицкий Игорь"
        return f"{mess}\n"

    def __del__(self):
        del self.raz
        del self.raz0
